import { _decorator, Component, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('ShakeComponent')
export class ShakeComponent extends Component {
    @property
    defaultFrequency: number = 15; // 震动频率，单位为 Hz

    @property
    defaultAmplitude: number = 8; // 振幅

    @property
    defaultDuration: number = 0.5; // 持续时间，单位为秒


    frequency: number = 15; // 震动频率，单位为 Hz
    duration: number = 0.5; // 持续时间，单位为秒
    amplitude: number = 8; // 振幅


    private shakeTime: number = 0;
    private originalPosition: Vec3 = new Vec3();

    isShaking = false

    start() {
        this.shakeTime = this.duration
        // this.schedule(() => { this.shake() }, 3)

    }

    update(dt: number) {
        if (this.isShaking) {
            if (this.shakeTime < this.duration) {
                const t = (this.frequency * this.shakeTime * Math.PI * 2); // 计算当前时间的相位
                const offset = new Vec3(Math.sin(t*this.node.scale.x>0?1:-1) * this.amplitude, Math.cos(t) * this.amplitude, 0);
                this.node.position = offset;
                this.shakeTime += dt;
            } else {
                this.node.setPosition(this.originalPosition)
                //this.node.position = this.originalPosition.clone();
                this.isShaking = false
            }
        }
    }

    stopShake(){
        this.node.setPosition(this.originalPosition)
        this.isShaking=false
    }

    shake(duration = this.defaultDuration, amplitude = this.defaultAmplitude, frequency = this.defaultFrequency) {
        if (this.isShaking && this.duration - this.shakeTime > duration && this.amplitude > amplitude && this.frequency > frequency) {
            return
        }
        this.duration = duration
        this.amplitude = amplitude
        this.frequency = frequency

        this.originalPosition = this.node.position.clone();
        this.shakeTime = 0;
        this.isShaking = true
    }
}
